package com.arcvideo.acsplayer.utils;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;

public class UriUtil {
	private static String TAG = UriUtil.class.getSimpleName();

	public static boolean isInputTextValid(String strText) {
		if (null == strText || 0 == strText.length())
			return false;

		if (!strText.toLowerCase().startsWith("http://") && !strText.startsWith("rtsp://"))
			return false;

		String strForbidden = "\\*<>|\n";
		int nStrForbidLen = 0;
		boolean bValid = true;

		nStrForbidLen = strForbidden.length();
		for (int i = 0; i < strText.length(); i++) {
			for (int j = 0; j < nStrForbidLen; j++) {
				if (strText.charAt(i) == strForbidden.charAt(j)) {
					bValid = false;
					break;
				}
			}
		}
		return bValid;
	}

	public static String uriToFilePath(Context activity, Uri uri) {
		if (null == uri || null == activity) {
			return null;
		}
		LogUtil.d(TAG, "uri=" + uri.toString());
		String tempString = null;
		Cursor cur = null;
		if (uri.toString().startsWith("http://")) {
			tempString = uri.toString();
			tempString = tempString.replaceAll("%20", " ");
		} else if (uri.toString().startsWith("file://")) {
			tempString = uri.toString().substring(7);
			tempString = tempString.replaceAll("%20", " ");
			tempString = tempString.replaceAll("%25", "%");
		} else {
			ContentResolver cr = activity.getContentResolver();

			cur = cr.query(uri, null, null, null, null);
			if (null != cur) {
				if (cur.moveToFirst()) {
					int idIndex = cur.getColumnIndex(MediaStore.Audio.Media.DATA);
					tempString = cur.getString(idIndex);
				}
			}
		}

		if (cur != null) {
			cur.close();
		}

		return tempString;
	}
}
